/* Copyright 2011 Gilberto Pacheco Gallegos.
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use
 * this file except in compliance with the License. You may obtain a copy of the
 * License at
 *     http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software distributed
 * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
 * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific
 * language governing permissions and limitations under the License. */
package net.ramptors.dominiobd.server;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import net.ramptors.dominiobd.client.ServicioGrupos;
import net.ramptors.dominiobd.client.entity.Grupo;

/**
 * @author Gilberto Pacheco Gallegos
 */
public class ServicioGruposImpl extends RemoteServiceServlet
    implements ServicioGrupos {
  private static final EntityManagerFactory emf = EMF.getEmf();
  @Override
  public List<Grupo> buscaTodo() {
    final EntityManager em = emf.createEntityManager();
    try {
      @SuppressWarnings("unchecked")
      final List<Grupo> lista = em.createQuery("SELECT o FROM Grupo o ORDER BY o.id").
          getResultList();
      return new ArrayList<Grupo>(lista);
    } finally {
      em.close();
    }
  }
  @Override
  public Grupo agrega(final Grupo objeto) {
    final EntityManager em = emf.createEntityManager();
    final EntityTransaction tx = em.getTransaction();
    try {
      tx.begin();
      em.persist(objeto);
      tx.commit();
      return objeto;
    } finally {
      if (tx.isActive()) {
        tx.rollback();
      }
      em.close();
    }
  }
  @Override
  public Grupo modifica(final Grupo objeto) {
    final EntityManager em = emf.createEntityManager();
    final EntityTransaction tx = em.getTransaction();
    try {
      tx.begin();
      final Grupo modificado = em.merge(objeto);
      tx.commit();
      return modificado;
    } finally {
      if (tx.isActive()) {
        tx.rollback();
      }
      em.close();
    }
  }
  @Override
  public void elimina(final String id) {
    final EntityManager em = emf.createEntityManager();
    final EntityTransaction tx = em.getTransaction();
    try {
      tx.begin();
      final Grupo objeto = em.find(Grupo.class, id);
      if (objeto != null) {
        em.remove(objeto);
      }
      tx.commit();
    } finally {
      if (tx.isActive()) {
        tx.rollback();
      }
      em.close();
    }
  }
}